/**
 * 测试死锁的两种模式，1是循环加锁，2是两个线程,各自持有一把锁,请求另一把
 * @author: sundx
 * @date: 2020-05-27 16:50:00
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-27 20:53:40
 */
#include <iostream>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int counter;

void *lockMyself(void *);

int main() {
  pthread_t tid;
  int ret;
  ret = pthread_create(&tid, nullptr, lockMyself, nullptr);
  if (ret < 0) {
    std::cout << "pthread_create failed " << strerror(ret) << std::endl;
  }
  ret = pthread_join(tid, nullptr);
  if (ret < 0) {
    std::cout << "pthread_join failed " << strerror(ret) << std::endl;
  }
  ret = pthread_mutex_destroy(&mutex);
  if (ret < 0) {
    std::cout << "pthread_destroy failed " << strerror(ret) << std::endl;
  }
  pthread_exit(nullptr);
  return 0;
}

void *lockMyself(void *argv) {
  pthread_mutex_lock(&mutex);
  pthread_mutex_lock(&mutex);
  std::cout << counter << std::endl;
  pthread_mutex_unlock(&mutex);
  return nullptr;
}